package org.shopping.web.admin;

import org.apache.commons.beanutils.BeanUtils;
import org.shopping.domain.Admin;
import org.shopping.service.admin.AdminService;
import org.shopping.service.admin.impl.AdminServiceImpl;
import org.shopping.utils.UUIDUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/AdminRegisterController")
public class AdminRegisterController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        try {
            // 处理响应中文的乱码问题
            response.setContentType("text/html;charset=utf-8");
            AdminService adminService = new AdminServiceImpl();
            // 异步校验注册账号是否存在
            String count = request.getParameter("username");
            boolean countExist = adminService.checkCountExist(count);
            if(countExist){
                //response.getWriter().write("yes");
                request.setAttribute("registerError","账号已经存在！");
                request.getRequestDispatcher("/register.jsp").forward(request,response);
                return;// 结束当前方法,通俗的来讲后面代码不再执行了
            }

            // 获取注册页面提交的账号信息
            Map<String, String[]> map = request.getParameterMap();
            // 封装到Admin这个bean对象
            Admin adminForm = new Admin();
            BeanUtils.populate(adminForm,map);
            // 补全数据 : 主键aid
            adminForm.setAid(UUIDUtils.randomKey());
            // 创建业务层对象Service
            // AdminService adminService = new AdminServiceImpl();
            boolean flag = adminService.registerAdmin(adminForm);
            // 判断注册是否成功
            // 资源跳转
            if(flag==true){
                // 注册成功,跳转到登录页面
                response.sendRedirect(
                        "http://localhost:8080/"+
                                request.getContextPath()+  // 获取部署的项目访问路径
                                "/login.jsp"
                        );
            }else{
                // 注册失败,跳转到注册页面
                request.setAttribute("registerError","注册失败");
                request.getRequestDispatcher("/register.jsp").forward(request,response);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        doPost(request, response);
    }
}
